package com.fourth_groups.shopping121store.ui.category.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.fourth_groups.shopping121store.Constants;
import com.fourth_groups.shopping121store.R;
import com.fourth_groups.shopping121store.bean.CategoryGoodsDetailBean;
import com.fourth_groups.shopping121store.bean.CategoryGroupRightBean;
import com.fourth_groups.shopping121store.http.OkHttpClientUtils;
import com.fourth_groups.shopping121store.ui.GoodsDetailActivity;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.CommonAdapter;
import com.fourth_groups.shopping121store.ui.category.adapter.commonadapter.ViewHolder;
import com.fourth_groups.shopping121store.utils.GsonImpl;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CategoryDetailActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener ,GridView.OnItemClickListener{
    private static final int SUCCESS = 1;
    private List<CategoryGoodsDetailBean.DataBean.ListBean> mList = new ArrayList<>();
    public static int sortStatePrice = 1;//价格类排序状态 （1：降序，2：升序）
    public static int sortStateFC = 1;//分成类排序状态（1：降序，2：升序）
    public static int pullState = 0;//上拉加载状态
    private String currentUrl;
    private int count=20;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS:
                    List<CategoryGoodsDetailBean.DataBean.ListBean> listbeans = (List<CategoryGoodsDetailBean.DataBean.ListBean>) msg.obj;
                    if(pullState == 0){
                        mList=listbeans;
                    }else if (pullState ==1){
//                        mList.retainAll(listbeans);
                        mList = listbeans;
                        pullState = 0;
                    }
                    adapter.setData(mList);
                    mPullGv.onRefreshComplete();
                    count=count+20;
                    break;
            }
        }
    };
    private PullToRefreshGridView mPullGv;
    private CommonAdapter<CategoryGoodsDetailBean.DataBean.ListBean> adapter;
    private RadioGroup mRg;
    private TextView tvTitle;
    private String url;
    private RadioButton mRbPrice;
    private RadioButton mRbFenCheng;
    private Toolbar mTbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_category_detail);

        initView();

        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        String title = bundle.getString("title");
        tvTitle.setText(title);
        CategoryGroupRightBean.DataBean.ChildrenBean.ListBean listBean = (CategoryGroupRightBean.DataBean.ChildrenBean.ListBean) bundle.getSerializable("listBean");
        int id = listBean.getId();

        url = Constants.ALL_CATEGORY_DEAIL_URL.replace("%d", Integer.toString(id));
        currentUrl = url;
        loadData(url);
        setGridViewData();
        //设置顶部导航监听
        mRg.setOnCheckedChangeListener(this);

        //设置上拉加载，下拉刷新
        mPullGv.setMode(PullToRefreshBase.Mode.BOTH);
        mPullGv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                count = 20;
                loadData(url);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                pullState = 1;
                if(count <=120){
                    String pullUrl = currentUrl.replace("limit=20","limit="+Integer.toString(count)).replace("offset=1","offset="+Integer.toString(mList.size()));
                    loadData(pullUrl);
                }else {
                    Toast.makeText(CategoryDetailActivity.this, "没有更多数据了...", Toast.LENGTH_SHORT).show();
                    mPullGv.onRefreshComplete();
                }
            }
        });

        mPullGv.setOnItemClickListener(this);

        //设置toolbar顶部导航返回
        mTbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    //初始化控件
    private void initView() {
        mPullGv = (PullToRefreshGridView) findViewById(R.id.gv_category_detail);
        tvTitle = (TextView) findViewById(R.id.tv_title_category_detail);
        mRg = (RadioGroup) findViewById(R.id.rg_category_detail_top_navigation);
        mRbPrice = (RadioButton) findViewById(R.id.rb_price_category_detail);
        mRbFenCheng = (RadioButton) findViewById(R.id.rb_fencheng_category_detail);
        mTbar = (Toolbar) findViewById(R.id.tbar_category_detail);
    }

    //设置适配器的数据
    private void setGridViewData() {
        adapter = new CommonAdapter<CategoryGoodsDetailBean.DataBean.ListBean>(this, R.layout.list_item_category_goods_detail) {
            @Override
            public void convert(ViewHolder helper, CategoryGoodsDetailBean.DataBean.ListBean item) {
                helper.setImageByUrl(CategoryDetailActivity.this, R.id.iv_logo_goods_detail, item.getImg());
                helper.setText(R.id.tv_title_category_goods_detail, item.getName());
                helper.setText(R.id.tv_now_price_goods_detail, "￥"+item.getPrice());
                helper.setText(R.id.tv_before_price_goods_detail,item.getMarket_price());
                helper.setText(R.id.tv_fencheng_category_goods_detail, item.getFencheng());
            }

        };
        mPullGv.setAdapter(adapter);
    }

    private void loadData(String url) {
        OkHttpClientUtils.getDataAsync(this, url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();
                CategoryGoodsDetailBean categoryGoodsDetailBean = GsonImpl.get().toObject(json, CategoryGoodsDetailBean.class);
                List<CategoryGoodsDetailBean.DataBean.ListBean> list = categoryGoodsDetailBean.getData().getList();
                Message message = new Message();
                message.what = SUCCESS;
                message.obj = list;
                mHandler.sendMessage(message);
            }
        }, new Object());
    }


    //分类排序存在bug，方法错误！暂时这样吧。。。
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_whole_category_detail:
                count = 20;
                loadData(url);
                break;
            case R.id.rb_sales_category_detail:
                count = 20;
                String newUrl2 = url.replace("type=1", "type=2");
                loadData(newUrl2);
                break;
            case R.id.rb_price_category_detail:
                count = 20;
                String newUrl3;
                if (sortStatePrice == 1) {
                    sortStatePrice = 2;
                    newUrl3 = url.replace("type=1", "type=3");

                } else {
                    sortStatePrice = 1;
                    newUrl3 = url.replace("type=1", "type=3").replace("sort=1", "sort=2");
                }
                loadData(newUrl3);
                break;
            case R.id.rb_fencheng_category_detail:
                count = 20;
                String newUrl4;
                if (sortStateFC == 1) {
                    sortStatePrice = 2;
                    newUrl4 = url.replace("type=1", "type=3");
                } else {
                    sortStateFC = 1;
                    newUrl4 = url.replace("type=1", "type=4").replace("sort=1", "sort=2");
                }
                loadData(newUrl4);
                break;
        }
        currentUrl = url;
    }

    //设置gridview的条目点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(CategoryDetailActivity.this, GoodsDetailActivity.class);
        intent.putExtra("id",mList.get(position).getId());
        startActivity(intent);
    }
}
